package org.example.mallchat.common.event.listener;

import lombok.extern.slf4j.Slf4j;
import org.example.mallchat.cache.UserBlackCacheHandler;
import org.example.mallchat.common.event.UserBlackEvent;
import org.example.mallchat.common.event.UserRegisterEvent;
import org.example.mallchat.dao.UserDao;
import org.example.mallchat.domain.entity.User;
import org.example.mallchat.domain.enums.IdempotentEnum;
import org.example.mallchat.domain.enums.ItemEnum;
import org.example.mallchat.domain.enums.UserStatusEnum;
import org.example.mallchat.service.iservice.ItemService;
import org.example.mallchat.websocket.service.WebSocketService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

import static org.example.mallchat.domain.enums.UserStatusEnum.NORMAL_STATUS;

/**
 * @author: zzh
 * @date: 2024/12/24 13:32:50
 * @version: 1.0
 */
// 事件监听器Spring容器的！
@Slf4j
@Component
public class UserBlackListener {
    @Resource
    private UserDao userDao;

    @Resource
    private WebSocketService webSocketService;

    @Resource
    private UserBlackCacheHandler userBlackCacheHandler;


    // 监听UserBlackEvent事件 推送给所有用户
    @Async// 异步处理
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT,fallbackExecution = true)
    public void sendBlackMsgToAll(UserBlackEvent event) {
        log.info("Received UserBlackEvent: sendBlackMsgToAll: {}", event);
        webSocketService.sendBlackMsgToAll(event.getUser().getId());
    }

    // 监听UserBlackEvent事件 修改拉黑用户的状态
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT,fallbackExecution = true)
    public void setBlackStatus(UserBlackEvent event) {
        log.info("Received UserBlackEvent setBlackStatus: {}", event);
        User user = event.getUser();
        user.setStatus(UserStatusEnum.BLACK_STATUS.getId());
        userDao.updateById(user);
    }

    // 监听UserBlackEvent事件 由于新的用户来了，需要将缓存的黑名单进行清空！
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT,fallbackExecution = true)
    public void clearBlackCache(UserBlackEvent event) {
        log.info("Received UserBlackEvent clearBlackCache: {}", event);
        userBlackCacheHandler.deleteCache();// 清空缓存
    }

}
